﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using FuturamaKassaWithGUI.Objects;
using FuturamaKassa;

namespace FuturamaKassaWithGUI.Parser {
    class XMLParser {

        XmlTextReader reader;

        /**
         * Constructor to create the parser class for the XML String
         */
        public XMLParser(string xmlString) {
            reader = new XmlTextReader(new StringReader(xmlString));
            reader.WhitespaceHandling = WhitespaceHandling.None;
        }

        /**
         * Function that actually parses the string and returns a list of products.
         */
        public List<Product> parse() {

            List<Product> products = new List<Product>();

            while (reader.Read()) {
                if (reader.NodeType == XmlNodeType.Element) {

                    if (reader.Name.Equals("product")) {

                        reader.Read();

                        int productId = reader.ReadElementContentAsInt();
                        string productName = reader.ReadElementContentAsString();
                        decimal productPrice = reader.ReadElementContentAsDecimal();

                        reader.Read();

                        int tagId = reader.ReadElementContentAsInt();
                        string tagName = reader.ReadElementContentAsString();

                        Tag tag = new Tag(tagId, tagName);

                        Product product = new Product(productId, productName, productPrice, tag);

                        products.Add(product);

                        Logger.Instance.writeLog("ID: " + productId + " Name: " + productName + " Price: " + productPrice + " TagId: " + tagId + " TagName: " + tagName);
                    }
                }
            }

            reader.Close();

            return products;
        }
    }
}
